package cn.display.pixelworksx7.ui.main

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import cn.display.pixelworksx7.R
import cn.display.pixelworksx7.constant.GlobalData
import cn.display.pixelworksx7.data.AppConfigInfoFile
import cn.display.pixelworksx7.databinding.AppIrisConfigFragmentBinding
import cn.display.pixelworksx7.threadpool.SystemThreadPool
import cn.display.pixelworksx7.util.IrisConfigUtil
import cn.display.pixelworksx7.util.ShellUtil
import kotlin.streams.toList


/*
 * A placeholder fragment containing a simple view.
*/

class AppIrisConfigFragment : Fragment() {
    // fragment 是否已加载
    private var TAG = "AppIrisConfigFragment"
    private var _binding: AppIrisConfigFragmentBinding? = null
    var editTextList = mutableListOf<EditText>()
    var buttonList = mutableListOf<Button>()
    var textView = mutableListOf<TextView>()

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        //可见的并且是初始化之后才加载
        var currentAppConfigInfo = GlobalData.appConfigInfo
        if (_binding != null && isVisibleToUser && currentAppConfigInfo != null) {
            if (currentAppConfigInfo.packageName != GlobalData.lastConfigPackageName) {
                for (index in 0..editTextList.size - 1) {
                    editTextList.get(index).setText("")
                }
            }
            var paramsList = GlobalData.params
            if (paramsList != null) {
                editParamsText(paramsList)
            }
            binding.packageName.text = GlobalData.appConfigInfo!!.packageName
            binding.appName.text = this.context?.let { GlobalData.appConfigInfo!!.applicationInfo.loadLabel(it.packageManager) }
            binding.appIcon.setImageDrawable(GlobalData.appConfigInfo!!.applicationInfo.loadIcon(this.context?.packageManager ?: null))
            val adapter = binding.touchHz.adapter as? ArrayAdapter<String>
            var isSearch = false
            adapter?.let {
                for (i in 0 until it.count) {
                    if (it.getItem(i) == GlobalData.touchConfigMap.get(GlobalData.appConfigInfo!!.packageName)) {
                        binding.touchHz.setSelection(i) // 找到后设置该项为选中状态
                        isSearch = true
                        break // 找到后退出循环
                    }
                }
                if (!isSearch) {
                    binding.touchHz.setSelection(0)
                }
            }
        }
    }

    // 编辑参数输入框
    fun editParamsText(paramsList: List<String>) {
        if (paramsList != null) {
            for (index in 0..paramsList.size - 1) {
                editTextList.get(index).setText(paramsList.get(index))
            }
        } else {
            for (i in 0..4) {
                editTextList.get(i).setText("")
            }
        }
    }

    fun editTextClearFocus () {
        for (editText in editTextList) {
            editText.clearFocus()
        }
    }

    fun hideIrisConfigView() {
        editTextList.forEach {
            it.visibility = View.GONE
        }
        buttonList.forEach {
            it.visibility = View.GONE
        }
        binding.irisConfigText.visibility = View.GONE
    }

    fun hideTouchView() {
        binding.touchHz.visibility = View.GONE
        binding.touchConfigText.visibility = View.GONE
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = AppIrisConfigFragmentBinding.inflate(inflater, container, false)
        val root = binding.root
        SystemThreadPool.getExecutorService().execute(Runnable {
            editTextList = mutableListOf<EditText>(binding.paramsA, binding.paramsB, binding.paramsC, binding.paramsD)
        })
        SystemThreadPool.getExecutorService().execute(Runnable {
            buttonList =
                mutableListOf<Button>(binding.gameMode, binding.clearConfig, binding.saveIrisConfig, binding.videoMode)
        })
        SystemThreadPool.getExecutorService().execute(Runnable {
            textView = mutableListOf(binding.irisConfigText, binding.touchConfigText)
        })

        if (GlobalData.isExistsIrisConfigBin) {
            // 保存按钮
            binding.saveIrisConfig.setOnClickListener {
                var params: List<String> = listOf<String>(
                    binding.paramsA.text.toString(),
                    binding.paramsB.text.toString(),
                    binding.paramsC.text.toString(),
                    binding.paramsD.text.toString()
                )
                params = params.parallelStream().filter { !it.trim().equals("") }.toList()
                setIrisConfigParam(
                    AppConfigInfoFile(
                        binding.packageName.text.toString(),
                        binding.appName.text.toString(),
                        params
                    )
                )
                if (GlobalData.isExistsTouchConfigBin) {
                    IrisConfigUtil.addTouchConfig(
                        binding.packageName.text.toString(),
                        binding.touchHz.selectedItem.toString()
                    )
                }
                editTextClearFocus()
            }
            // video模式
            binding.videoMode.setOnClickListener {
                var videoIrisConfigParamsList = resources.getStringArray(R.array.video_iris_config).toMutableList()
                editParamsText(videoIrisConfigParamsList)
                setIrisConfigParam(
                    AppConfigInfoFile(
                        binding.packageName.text.toString(),
                        binding.appName.text.toString(),
                        videoIrisConfigParamsList
                    )
                )
                if (GlobalData.isExistsTouchConfigBin) {
                    binding.touchHz.setSelection(0)
                    IrisConfigUtil.addTouchConfig(
                        binding.packageName.text.toString(),
                        binding.touchHz.selectedItem.toString()
                    )
                }
                editTextClearFocus()
            }
            // game模式
            binding.gameMode.setOnClickListener {
                var gameIrisConfigParamsList = resources.getStringArray(R.array.game_iris_config).toMutableList()
                editParamsText(gameIrisConfigParamsList)
                setIrisConfigParam(
                    AppConfigInfoFile(
                        binding.packageName.text.toString(),
                        binding.appName.text.toString(),
                        gameIrisConfigParamsList
                    )
                )
                if (GlobalData.isExistsTouchConfigBin) {
                    binding.touchHz.setSelection(GlobalData.touchModeShell.size - 1)
                    IrisConfigUtil.addTouchConfig(
                        binding.packageName.text.toString(),
                        binding.touchHz.selectedItem.toString()
                    )
                }
                editTextClearFocus()
            }
            // 清空配置
            binding.clearConfig.setOnClickListener {
                if (GlobalData.irisConfigMap.containsKey(binding.packageName.text.toString())) {
                    var params: List<String> = listOf<String>(
                        "",
                        "",
                        "",
                        ""
                    )
                    editParamsText(params)
                }
                if (GlobalData.touchConfigMap.containsKey(binding.packageName.text.toString())) {
                    if (GlobalData.isExistsTouchConfigBin) {
                        binding.touchHz.setSelection(0)
                    }
                }
                IrisConfigUtil.clearConfigByPackageName(binding.packageName.text.toString())
                editTextClearFocus()
            }
        } else {
            hideIrisConfigView()
        }
        // 启动软件
        binding.startApp.setOnClickListener {
            val packageName: String = binding.packageName.text.toString()
            val intent: Intent? = this.context?.packageManager?.getLaunchIntentForPackage(packageName)
            startActivity(intent)
            if (GlobalData.isExistsIrisConfigBin) {
                if (GlobalData.irisConfigMap.containsKey(packageName)) {
                    // 有配置
                    var paramsCommandList =
                        GlobalData.irisConfigMap.get(packageName)?.stream()?.map { it ->
                            IrisConfigUtil.irisConfigBinFilePath + " " + it
                        }?.toList()
                    // Log.w(MainActivity.tag, "有配置" + paramsCommandList.toString())
                    if (paramsCommandList != null) {
                        IrisConfigUtil.disableIris()
                        ShellUtil.execCommand(paramsCommandList.toTypedArray(), true)
                    }
                }
            }
        }

        if (GlobalData.isExistsTouchConfigBin) {
            binding.touchHz.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                    val selectedItem = parent.getItemAtPosition(position) as String
                    if (!"TextView".equals(binding.packageName.text.toString())) {
                        SystemThreadPool.getExecutorService().execute(Runnable {
                            IrisConfigUtil.addTouchConfig(binding.packageName.text.toString(), selectedItem)
                        })
                    }
                    // 处理选中项
                }

                override fun onNothingSelected(parent: AdapterView<*>) {
                    // 用户没有选择任何选项
                }
            }
        } else {
            hideTouchView()
        }
        return root
    }

    fun setIrisConfigParam(appConfigInfoFile: AppConfigInfoFile) {
        var addIrisConfigResult = IrisConfigUtil.addIrisConfig(appConfigInfoFile)
        if (addIrisConfigResult > 0) {
            IrisConfigUtil.loadIrisConfigFileParseToMap()
        } else if (addIrisConfigResult == 0) {
        }
    }

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): AppIrisConfigFragment {
            return AppIrisConfigFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
